package com.ec.auth.security.handle;

import com.ec.auth.datasource.DynamicDataSourceContextHolder;
import com.ec.auth.manager.AsyncManager;
import com.ec.auth.manager.factory.AsyncFactory;
import com.ec.auth.web.service.TokenService;
import com.ec.common.constant.Constants;
import com.ec.common.constant.I18nConstant;
import com.ec.common.core.domain.AjaxResult;
import com.ec.common.core.domain.entity.SysUser;
import com.ec.common.core.domain.model.LoginUser;
import com.ec.common.utils.DateUtils;
import com.ec.common.utils.MessageUtils;
import com.ec.common.utils.ServletUtils;
import com.ec.common.utils.ip.IpUtils;
import com.ec.sys.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证成功
 */
@Component
@Slf4j
public class SuccessHandle implements AuthenticationSuccessHandler {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        LoginUser principal = (LoginUser) authentication.getPrincipal();

        // 记录登录日志
        String message = MessageUtils.message(I18nConstant.USER_LOGIN_SUCCESS);
        AsyncManager.me().execute(AsyncFactory.recordLoginInfo(principal.getUsername(), Constants.LOGIN_SUCCESS, message));
        principal.setTenant(request.getHeader("tenant"));
        // 记录登录信息
        recordLoginInfo(principal.getUserId());
        // 生成令牌
        String token = tokenService.createToken(principal);
        AjaxResult success = AjaxResult.success(message);
        success.put(Constants.TOKEN, token);
        // 请求结束删除localThread
        DynamicDataSourceContextHolder.clearDataSourceKey();
        ServletUtils.renderFailString(response, success);
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    private void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        boolean updated = userService.updateUserProfile(sysUser);
        if (updated) log.info("记录登录信息");
    }

}
